<?php

namespace app\system\controller;

use app\common\controller\Excel;
use app\common\lib\Redis;
use think\Db;
use think\Exception;
use think\Request;

class Backup extends Common{
    protected $table = 'backup',$name = '备份',$mysql_bin='mysql',$mysqldump_bin = 'mysqldump';

    function __construct(Request $request = null){
        parent::__construct($request);
    }

    function getMysqlBin($bin){
        $password = config('database.password')?' -p'.config('database.password'):'';
        return config('mysql_path').$bin.' -h '.config('database.hostname').' -P '.config('database.hostport').' -u '.config('database.username').' '.$password.' '.config('database.database');
    }
    function select(){
        $where = ['t.is_del'=>'0'];
        if(input('keyword')) $where['t.title'] = ['like','%'.input('keyword').'%'];
        if(input('start_time')) $where['t.create_time'] = ['>=',strtotime(input('start_time'))];
        if(input('end_time')) $where['t.create_time'] = ['<=',strtotime(input('end_time').' +1 day')];
        if(input('start_time') && input('end_time')) $where['t.create_time'] = ['between',[strtotime(input('start_time')),strtotime(input('end_time').' +1 day')]];

        return $list = db($this->table.' t')->where($where)->order('t.id asc');
    }
    function index(){
        //需要过滤的文件
        $files = array_slice(scandir('backups',1),0,-2);
        $list = [];
        if(is_array($files)){
            foreach($files as $k=>$v){
                $filesize = filesize('backups/'.$v);
                if($filesize < 1024){
                    $size = sprintf("%01.2f", $filesize)."B";
                }elseif($filesize < 1024 * 1024){
                    $size = sprintf("%01.2f", ($filesize / 1024))."KB";
                }elseif($filesize < 1024 * 1024 * 1024){
                    $size = sprintf("%01.2f", ($filesize / (1024 * 1024)))."MB";
                }elseif($filesize < 1024 * 1024 * 1024 * 1024){
                    $size = sprintf("%01.2f", ($filesize / (1024 * 1024 * 1024)))."GB";
                }
                $is_del = strstr($v,'auto')==false?1:0;
                $list[] = [
                    'file'=>$v,
                    'size'=>$size,
                    'create_time'=>filemtime('backups/'.$v),
                    'is_del'=>$is_del,
                ];
            }
        }
        $this->assign('list',$list);

        return $this->fetch();
    }
    function add($auto=0){
        try{
            $path = "backups/";//备份存放路径
            if($auto==1){
                $name = config('database.database')."_auto_".date("YmdHis").".sql";//备份名称
            }else{
                $name = config('database.database')."_".date("YmdHis").".sql";//备份名称
            }
            $filePath = $path.$name;
            // 备份命令组合
            $exec = $this->getMysqlBin($this->mysqldump_bin).' > '.$filePath;
            set_time_limit(0);
            exec($exec,$output,$res);
            if($res!='0'){
                return return_message('0','备份失败','4');
            }else{
                return return_message('1','备份成功');
            }
        }catch(Exception $e){
            return return_message('0','备份失败','2');
        }
    }

    /**
     * 还原备份
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function import($file){
        $sql_file = "backups/".$file;
        if(!file_exists($sql_file)) return ['status'=>'1','message'=>'文件不存在，请检查','icon'=>'2'];
        //还原备份前先做一个备份
        $add_res = $this->add();
        // if($add_res['status']!=1) return ['status'=>'0','message'=>lang('数据备份失败'),'icon'=>'2'];
        //还原备份
        $exec = $this->getMysqlBin($this->mysql_bin).' < '.$sql_file;
        set_time_limit(0);
        exec($exec, $output,$res);
        if($res!='0'){
            return return_message('0','备份还原','4');
        }else{
            return return_message('1','备份还原成功');
        }
    }
    function delete(array $file){
        foreach($file as $k=>$v){
            unlink('backups/'.$v);
        }
    }
    /**
     * @return array
     */
    function clear(){
        //清空前先备份数据
        $add_res = $this->add();
        if($add_res['status']!=1) return ['status'=>'0','message'=>'数据备份失败','icon'=>'2'];
           //清空推广码
        $res=db('user')->where('id!=1')->field('id')->select();
        foreach($res as $k=>$v){
            unlink('qrcode/invite/'.$v['id'].'.png');
        }
        $sql_file = 'clear.sql';
        //还原备份
        $exec = $this->getMysqlBin($this->mysql_bin).' < '.$sql_file;
        set_time_limit(0);
        exec($exec, $output, $res);
        if($res != '0'){
            return ['status'=>'0','message'=>'数据清空','icon'=>'2'];
        }else{
         
             //清空相关暂存信息
             $group = new \app\index\model\Group();
             $group->clear_redis();
            return ['status'=>'1','message'=>'数据清空成功','icon'=>'1'];
        }
    }
}